# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# 作者   : 王宗龙
# 文件     : user.py
# 时间     : 2020/12/9 15:30
# 开发工具 : PyCharm
from fastapi import FastAPI,Request
from fastapi.middleware.cors import CORSMiddleware
from apps.base.log import logger,conf

def Ok(data='',msg="ok"):
    return {"data":data,"msg":msg,"code":0 }

def Fail(data,msg):
    return {"data":data,"msg":msg,"code":1 }

class Page:
    def __init__(self,pageindex: int=1 ,pagesize: int = 10,search:str=''):
        self.pageindex=pageindex
        self.offset=(pageindex-1)*pagesize
        self.limit=pagesize
        self.search = search

def cors(app: FastAPI):
    """
    支持跨域
    """
    app.add_middleware(
        CORSMiddleware,
        # allow_origins=['http://localhost:8081'],  # 有效, 但是本地vue端口一直在变化, 接口给其他人用也不一定是这个端口
        # allow_origins=['*'],   # 无效 bug allow_origins=['http://localhost:8081']
        allow_origin_regex='https?://.*',  # 改成用正则就行了
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )


def Access(app: FastAPI):
    @app.middleware("http")
    async def logger_request(request: Request, call_next):
        logger.info(f"{request.method}:{request.url}  |from:{request.client.host}")
        response = await call_next(request)
        return response
